#!/bin/sh

# the defined variables should be:
# CONSPIRE_DEMAND_JOB
# CONSPIRE_WRITEABLEDIR
# CONSPIRE_KEYID
# CONSPIRE_TMAX
# CONSPIRE_CLUSTERID

export CONSPIRE_JOBID=$PBS_JOBID
if [ "$CONSPIRE_CLUSTERID" = "emerald" ]; then
   export CONSPIRE_JOBID=$LSB_JOBID
fi
mkdir -p compute_$CONSPIRE_KEYID
mv $CONSPIRE_KEYID.pub compute_$CONSPIRE_KEYID/
mv $CONSPIRE_KEYID.prv compute_$CONSPIRE_KEYID/
cd compute_$CONSPIRE_KEYID
if [ -n "`which wget`" ]; then
   wget http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/brokerkeyname -O brokerkeyname
   wget http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/`cat brokerkeyname`.pub -O `cat brokerkeyname`.pub
   wget http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/compute -O compute
else
   if [ -n "`which curl`" ]; then
      curl http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/brokerkeyname > brokerkeyname
      curl http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/`cat brokerkeyname`.pub > `cat brokerkeyname`.pub
      curl http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/compute > compute
   else
      echo "Could not find suitable downloading program!"
   fi
fi
chmod +x compute
mkdir -p work
ldd ./compute
touch work/cluster_used_was_$CONSPIRE_CLUSTERID
echo $LD_LIBRARY_PATH
LD_LIBRARY_PATH=$HOME/lib ./compute -n $CONSPIRE_BROKERHOST -p $CONSPIRE_BROKERPORT -d $PWD/work -z $CONSPIRE_KEYID -t $CONSPIRE_TMAX -j $CONSPIRE_JOBID -f $CONSPIRE_DEMAND_JOB
rm $CONSPIRE_KEYID.pub
rm $CONSPIRE_KEYID.prv
cd ..
rm -fr compute_$CONSPIRE_KEYID
rm -fr bootstrap_$CONSPIRE_KEYID.sh
